<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生管理系统</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background-color: #409EFF;
            color: white;
            padding: 20px 0;
            text-align: center;
            margin-bottom: 30px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .card {
            margin-bottom: 30px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            border-radius: 4px;
        }
        .operation-panel {
            padding: 20px;
            background-color: #fff;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .student-info {
            padding: 20px;
            background-color: #fff;
            border-radius: 4px;
        }
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 120px;
            height: 120px;
            line-height: 120px;
            text-align: center;
        }
        .avatar {
            width: 120px;
            height: 120px;
            display: block;
        }
        .footer {
            text-align: center;
            margin-top: 30px;
            color: #909399;
            font-size: 14px;
        }
        .student-photo {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .photo-placeholder {
            width: 100px;
            height: 100px;
            background-color: #f5f7fa;
            border: 1px dashed #ddd;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #909399;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 顶部导航 -->
    <div class="header">
        <h1>学生信息管理系统</h1>
    </div>

    <div class="container">
        <!-- 查询操作面板 -->
        <el-card class="card">
            <div slot="header">
                <span>查询学生信息</span>
            </div>
            <div class="operation-panel">
                <el-form :inline="true" :model="queryForm" class="demo-form-inline">
                    <el-form-item label="学生ID">
                        <el-input v-model="queryForm.id" placeholder="请输入学生ID"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onQuery" icon="el-icon-search">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 查询结果显示 -->
            <div class="student-info" v-if="currentStudent.id">
                <el-descriptions title="学生详细信息" border>
                    <el-descriptions-item label="ID">{{ currentStudent.id }}</el-descriptions-item>
                    <el-descriptions-item label="姓名">{{ currentStudent.name }}</el-descriptions-item>
                    <el-descriptions-item label="年龄">{{ currentStudent.age }}</el-descriptions-item>
                    <el-descriptions-item label="性别">
                        <el-tag size="small">{{ currentStudent.gender === 'M' ? '男' : '女' }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="照片">
                        <div v-if="currentStudent.photoUrl">
                            <img
                                    :src="currentStudent.photoUrl"
                                    class="student-photo"
                                    @error="handleImageError"
                                    :alt="currentStudent.name + '的照片'">
                            <div v-if="imageLoadError" class="photo-placeholder">
                                <i class="el-icon-picture-outline"></i>
                                <span>图片加载失败</span>
                            </div>
                        </div>
                        <div v-else class="photo-placeholder">
                            <span>无照片</span>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-card>

        <!-- 添加学生表单 -->
        <el-card class="card">
            <div slot="header">
                <span>添加新学生</span>
            </div>
            <div class="operation-panel">
                <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="addForm.name" placeholder="请输入学生姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="年龄" prop="age">
                        <el-input v-model.number="addForm.age" placeholder="请输入学生年龄"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="addForm.gender">
                            <el-radio label="M">男</el-radio>
                            <el-radio label="F">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="照片" prop="photoFile">
                        <el-upload
                                class="avatar-uploader"
                                action="#"
                                :show-file-list="false"
                                :before-upload="beforeAvatarUpload"
                                :http-request="handleAvatarUpload">
                            <img v-if="addForm.photoUrl" :src="addForm.photoUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onAdd('addForm')">添加学生</el-button>
                        <el-button @click="resetForm('addForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>

        <div class="footer">
            <p>学生信息管理系统 © 2025</p>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            // 年龄验证规则
            const checkAge = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('年龄不能为空'));
                }
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        if (value < 1 || value > 120) {
                            callback(new Error('年龄必须在1到120之间'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };

            return {
                // 查询表单数据
                queryForm: {
                    id: ''
                },
                // 添加表单数据
                addForm: {
                    name: '',
                    age: '',
                    gender: 'M',
                    photoFile: null,
                    photoUrl: ''
                },
                // 当前查询到的学生信息
                currentStudent: {},
                // 图片加载错误标志
                imageLoadError: false,
                // 表单验证规则
                rules: {
                    name: [
                        { required: true, message: '请输入学生姓名', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                    ],
                    age: [
                        { required: true, validator: checkAge, trigger: 'blur' }
                    ],
                    gender: [
                        { required: true, message: '请选择性别', trigger: 'change' }
                    ]
                }
            };
        },
        methods: {
            // 查询学生信息
            onQuery() {
                if (!this.queryForm.id) {
                    this.$message.error('请输入学生ID');
                    return;
                }

                // 重置图片错误状态
                this.imageLoadError = false;

                axios.get(`/student/find/${this.queryForm.id}`)
                    .then(response => {
                        if (response.data.code === 1) {
                            this.currentStudent = response.data.data;

                            // 确保图片URL是完整URL（如果不是的话）
                            if (this.currentStudent.photoUrl &&
                                !this.currentStudent.photoUrl.startsWith('http')) {
                                // 这里可以根据您的实际URL结构进行调整
                                this.currentStudent.photoUrl = 'https://nanhua-ossoss.oss-cn-guangzhou.aliyuncs.com/student/' +
                                    this.currentStudent.photoUrl;
                            }

                            this.$message.success('查询成功');
                        } else {
                            this.$message.error(response.data.message || '查询失败');
                            this.currentStudent = {};
                        }
                    })
                    .catch(error => {
                        this.$message.error('查询失败: ' + (error.response?.data?.message || error.message));
                        this.currentStudent = {};
                        console.error('查询错误:', error);
                    });
            },

            // 处理图片加载错误
            handleImageError() {
                this.imageLoadError = true;
                console.error('图片加载失败，URL:', this.currentStudent.photoUrl);
            },

            // 上传前检查
            beforeAvatarUpload(file) {
                const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPGOrPNG) {
                    this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPGOrPNG && isLt2M;
            },

            // 处理照片上传
            handleAvatarUpload(params) {
                this.addForm.photoFile = params.file;

                // 创建预览图
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.addForm.photoUrl = e.target.result;
                };
                reader.readAsDataURL(params.file);
            },

            // 添加学生
            onAdd(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // 创建FormData对象，用于文件上传
                        const formData = new FormData();
                        formData.append('name', this.addForm.name);
                        formData.append('age', this.addForm.age);
                        formData.append('gender', this.addForm.gender);

                        if (this.addForm.photoFile) {
                            formData.append('photoFile', this.addForm.photoFile);
                        }

                        axios.post('/student/add', formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        })
                            .then(response => {
                                if (response.data.code === 1) {
                                    this.$message.success('添加学生成功');
                                    this.resetForm(formName);
                                } else {
                                    this.$message.error(response.data.message || '添加失败');
                                }
                            })
                            .catch(error => {
                                this.$message.error('添加失败: ' + (error.response?.data?.message || error.message));
                                console.error('添加错误:', error);
                            });
                    } else {
                        this.$message.error('请填写正确的表单信息');
                        return false;
                    }
                });
            },

            // 重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.addForm.photoFile = null;
                this.addForm.photoUrl = '';
            }
        }
    });
</script>
</body>
</html>